package com.wxxymaker.model.dao;

import com.wxxymaker.model.entity.Shop;
import com.wxxymaker.model.entity.StageCount;
import com.wxxymaker.model.entity.Stage;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * @Author: Soft
 * @Date: 2018/5/3 23:16
 * @Desc:
 */
public interface StageCountDao extends JpaRepository<StageCount, Integer>, JpaSpecificationExecutor<StageCount> {

    /**
     * 根据阶段id清除阶段统计与对应阶段间的外键关系，为了实现删除阶段而不会删除阶段统计信息
     * @param stageId  阶段id
     */
    @Modifying
    @Query(value = "update t_stage_count set stage_id=null where stage_id=?1", nativeQuery = true)
    int clearRefWithStage(Integer stageId);

    @Modifying
    @Query("delete from StageCount sc where sc.stage = ?1")
    int deleteByStage(Stage stage);

    @Query("select sc from StageCount sc where sc.shop=?1 order by sc.countTime desc")
    List<StageCount> findAllByShop(Shop shop);

    @Query(value = "select avg(total) from t_stage_count where shop_id=?1", nativeQuery = true)
    double shopAvgTotal(Integer shopId);

    StageCount findByStageAndShop(Stage stage, Shop shop);
}
